package com.ada.secure;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;

public class ECDSAExample {
    public static void main(String[] args) throws Exception {
        // Generate ECDSA key pair
        KeyPair keyPair = generateECDSAKeyPair();

        // Data to be signed
        String data = "Hello, ECDSA!";
        byte[] dataBytes = data.getBytes();

        // Sign the data using the private key
        byte[] signature = signData(dataBytes, keyPair.getPrivate());

        // Verify the signature using the public key
        boolean verified = verifySignature(dataBytes, signature, keyPair.getPublic());

        System.out.println("Data: " + data);
        System.out.println("Signature: " + new String(signature));
        System.out.println("Signature Verified: " + verified);
    }

    // Generate ECDSA key pair
    public static KeyPair generateECDSAKeyPair() throws Exception {
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("EC");
        keyPairGenerator.initialize(256); // ECDSA key size in bits
        return keyPairGenerator.generateKeyPair();
    }

    // Sign data using ECDSA private key
    public static byte[] signData(byte[] data, PrivateKey privateKey) throws Exception {
        Signature ecdsa = Signature.getInstance("SHA256withECDSA");
        ecdsa.initSign(privateKey);
        ecdsa.update(data);
        return ecdsa.sign();
    }

    // Verify ECDSA signature using public key
    public static boolean verifySignature(byte[] data, byte[] signature, PublicKey publicKey) throws Exception {
        Signature ecdsa = Signature.getInstance("SHA256withECDSA");
        ecdsa.initVerify(publicKey);
        ecdsa.update(data);
        return ecdsa.verify(signature);
    }
}
